package com.nwpu.coursesupport.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.nwpu.coursesupport.criteria.ResourceSearchCriteria;
import com.nwpu.coursesupport.entity.Resource;
import com.nwpu.coursesupport.entity.Student;
import com.nwpu.coursesupport.entity.bean.JSONResult;
import com.nwpu.coursesupport.enumeration.FileType;
import com.nwpu.coursesupport.enumeration.StatusType;
import com.nwpu.coursesupport.service.imple.ResourceService;
import com.nwpu.coursesupport.service.param.ResourceServiceParam.DeleteParam;
import com.nwpu.coursesupport.tool.FileUtil;
import com.nwpu.coursesupport.tool.MD5Util;
import com.nwpu.coursesupport.tool.WebUtils;

@Controller
@RequestMapping("/resource")
public class FileController extends AbstractController{
	
	@Autowired
	private ResourceService resourceService;
	
	
	//editUpload和editAnswerUpload需要修改，目前只能将文件域规定为editor-task和editor-answer
	@RequestMapping(value="/editUpload",method=RequestMethod.POST)
	@ResponseBody
	public String editUpload(@RequestParam("editor-task")MultipartFile file,HttpServletRequest request){
		if(file==null){
			return "上传失败";
		}
		//format the name of file: add uploader in the name
		String fnf = file.getOriginalFilename();
		String format = this.resourceService.formatName(fnf);
		
		String key = save(format,file);
		String contextPath=getSetting().getContextPath();
		//需修改--如何获取这块的地址
		return contextPath+"/resource/picture/"+key;
        
    }
	@RequestMapping(value="/editAnswerUpload",method=RequestMethod.POST)
	@ResponseBody
	public String editAnswerUpload(@RequestParam("editor-answer")MultipartFile file,HttpServletRequest request){
		if(file==null){
			return "上传失败";
		}
		
		//format the name of file: add uploader in the name
		String fnf = file.getOriginalFilename();
		String format = this.resourceService.formatName(fnf);
		
		String key = save(format, file);
		String contextPath=getSetting().getContextPath();
		//需修改--如何获取这块的地址
		return contextPath+"/resource/picture/"+key;
        
    }
		
	@RequestMapping(value="/deleteFile",method=RequestMethod.POST)
	@ResponseBody
	public JSONResult deleteFile(@RequestParam("key") String key){
		JSONResult result = new JSONResult();
		result.fail();
		if(key == null || key == ""){
			logger.error("参数错误");
			result.fail("参数错误");
			return result;
		}
		ArrayList<String> list = new ArrayList<String>();
		list.add(key);
		
		DeleteParam dp = new DeleteParam();
		dp.setKeys(list);
		try {
			result = this.resourceService.delete(dp);
		} catch (Exception e) {
			logger.error(e.getMessage());
			result.fail(e.getMessage()+"删除异常");
			return result;
		}	
		
	    return result;
	}
	
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	@ResponseBody
	public JSONResult delete(@RequestParam("list") ArrayList<String> list){
		
		JSONResult result = new JSONResult();
		result.fail();
		if(list.size()<=0){
			logger.error("参数错误");
			result.fail("参数错误");
			return result;
		}
		DeleteParam dp = new DeleteParam();
		dp.setKeys(list);
		try {
			result = this.resourceService.delete(dp);
		} catch (Exception e) {
			logger.error(e.getMessage());
			result.fail(e.getMessage()+"删除异常");
			return result;
		}
        return result;
	}
	@RequestMapping(value="/upload",method=RequestMethod.POST)
	@ResponseBody
	public JSONResult upload(@RequestParam("file")MultipartFile file){
		JSONResult rst=new JSONResult();
		rst.fail();
		if(file==null){
			return rst.fail("参数有误");
		}
		//format file name
		String fnf = file.getOriginalFilename();
		String format = this.resourceService.formatName(fnf);
		
		String key=save(format, file);
		if(key==null){
			return rst.fail("上传失败");
		}
		
		rst.success();
		rst.addData("key", key);
		rst.addData("name",format);
		return rst;	
	}
	
	@RequestMapping(value="/batchUpload",method=RequestMethod.POST)
	@ResponseBody
	public JSONResult batchUpload(@RequestParam("files")MultipartFile [] files){
		JSONResult rst=new JSONResult();
		rst.fail();
		if(files.length<=0){
			return rst.fail("上传失败");
		}
		List<String> keys=new ArrayList<String>();
		List<String> names=new ArrayList<String>();
		int count=0;
		for(MultipartFile file : files){
			String key=save(file.getOriginalFilename(), file);
			if(key!=null){
				keys.add(key);
				names.add(file.getOriginalFilename());
				count++;
			}
		}
		rst.success();
		rst.addData("keys", keys);
		rst.addData("count", count);
		return rst;
	} 
	
	private String save(String fileName, MultipartFile f) {
		if (!f.isEmpty()) {
			Resource resource = new Resource();
			try {				
				resource.setFileName(fileName);
				resource.setFileType(FileUtil.getFileType(f.getOriginalFilename()));
				
				Date date = new Date();
				resource.setUploadDate(date);
				resource.setUploadId((Integer) getSession().getAttribute("id"));
				resource.setUploadName((String) getSession().getAttribute("username"));
				String uploadPath = this.getSetting().getUploadPath();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
				String dayPath = sdf.format(date);
				sdf = new SimpleDateFormat("HHmmssSSS");
				String secondPath = sdf.format(date);
				String key = MD5Util.md5(secondPath + f.getName());
				resource.setFileKey(key);
				
				String path = new StringBuilder().append(uploadPath).append(File.separator).append(dayPath)
						.append(File.separator).append(key).toString();
				resource.setUrl(path);
				File file=new File(path);
				if(!file.exists()){
					file.getParentFile().mkdirs();
					file.createNewFile();
				}
				f.transferTo(file);
			} catch (Exception e) {
				System.out.println(e);
				return null;
			} 
			this.resourceService.create(resource);
			return resource.getFileKey();
		}
		return null;
	}

	@RequestMapping("/picture/{key}")
	public void picture(@PathVariable("key")String key,HttpServletResponse response){
		Resource resource =this.resourceService.detail(key);
		if(resource==null){
			ResourceSearchCriteria sc=new ResourceSearchCriteria();
			sc.setType(FileType.UNLOAD);
			List<Resource> resources=this.resourceService.list(sc);
			if(resources==null||resources.size()<=0){
				WebUtils.sendJson(response,StatusType.WRONG,"该文件不存在");
			}else{
				WebUtils.sendFile(response, resources.get(0));
			}
		}else{
			WebUtils.sendFile(response, resource);
		}
	}
	
	@RequestMapping("/download/{key}")
	public void download(@PathVariable("key")String key,HttpServletResponse response){
		Resource resource =this.resourceService.detail(key);
		if(resource==null){
			WebUtils.sendJson(response,StatusType.WRONG,"该文件不存在");
		}else{
			WebUtils.sendFile(response, resource);
		}
	}
	
	@RequestMapping("/downloadFormat/{key}")
	public void downloadFormat(@PathVariable("key")String key,HttpServletResponse response){
		Resource resource =this.resourceService.detail(key);
		if(resource==null){
			WebUtils.sendJson(response,StatusType.WRONG,"该文件不存在");
		}else{
			Student student = this.resourceService.getStudent(resource.getUploadId());
			WebUtils.sendFileFormat(response, resource, student.getClassNumber(), student.getStudentCode(), student.getName());
		}
	}

}
